<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        noimmediate
        :elements="elements"
        @submit="handleSearch"
        @reset="handleReset"
      >
        <Button v-if="!imageShow" icon="add" type="plain" @click="handleAdd">新增</Button>
      </FilterForm>
    </Container>
    <Container height="fill">
      <div class="wraper">
        <div v-if="imageShow" class="image-srcc">
          <img src="../../../assets/image/archived.png" alt="" />
        </div>
        <Table
          :columns="tableColumns"
          :loading="tableLoading"
          :data="tableData"
          :pagination="{
            total: total,
            current: currentPage,
            pageSize: pageSize,
          }"
          @paginationChange="pageChange"
          @rowSelection="handleSelection"
        >
          <template #isOffsetting="{ row }">
            <el-switch
              style="display: block"
              disabled
              v-model="row.isOffsetting"
              :active-value="1"
              :inactive-value="0"
              active-color="#409EFF"
              inactive-color="#C0CCDA">
            </el-switch>
          </template>
          <template #caozuo="{ row }">
            <Tooltip v-if="!imageShow" content="编辑" icon="edit" @click="handleEdit(row)" />
            <Tooltip v-if="!imageShow" content="删除" icon="delete" @click="handleDelete(row)" />
          </template>
        </Table>
      </div>
      <!-- 新增、编辑 -->
      <Drawer
        ref="drawerRef"
        :title="title"
        :visible.sync="showDrawer"
        width="420px"
        :footer-btns="[
          {
            text: '确认',
            type: 'primary',
            loading: qrLoading,
            trigger: 'submit',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @submit="handleSubmit"
        @cancel="showDrawer = false"
      >
        <el-form
          v-if="showDrawer"
          ref="drawerForm"
          :model="drawerForm"
          :rules="drawerRules"
          label-width="140px"
          size="mini"
          class="demo-drawerForm"
        >
          <el-form-item label="目标科室：" prop="sdeptCode">
            <el-select
              v-model="drawerForm.sdeptCode"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in kzdptList"
                :key="item.code"
                :label="item.nameAndCode"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="源科室：" prop="ydeptCode">
            <el-select
              v-model="drawerForm.ydeptCode"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in kzdptList"
                :key="item.code"
                :label="item.nameAndCode"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="统计项目：" prop="itemCode">
            <el-select
              v-model="drawerForm.itemCode"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in statistical"
                :key="item.projectCode"
                :label="item.projectName"
                :value="item.projectCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="给予比例：" prop="piont">
            <el-input
              v-model.trim="drawerForm.piont"
              placeholder="请输入"
              type="text"
              clearable
            />
          </el-form-item>
          <el-form-item label="是否计入目标科室：" prop="isOffsetting">
            <el-switch
              style="display: block"
              v-model="drawerForm.isOffsetting"
              :active-value="1"
              :inactive-value="0"
              active-color="#409EFF"
              inactive-color="#C0CCDA">
            </el-switch>

          </el-form-item>
        </el-form>
      </Drawer>
    </Container>
  </ContainerGroup>
</template>
<script>
import {
  listByPeriod,
  getAssessmentCycleById,
  getAssessmentCyclePull,
  saveOrUpdateSysItemPiont,
  HISDeptCode,
  listAll,
  deleteSysItemPiont
} from '@/api/targetManagement'
export default {
  data() {
    return {
      qrLoading: false,
      btnType: 1,
      drawerForm: {
        sdeptCode: "",
        ydeptCode: "",
        itemCode: "",
        piont: "",
        isOffsetting: 0
      },
      drawerRules: {
        sdeptCode: [
          { required: true, message: "请选择目标科室", trigger: "change" },
        ],
        ydeptCode: [
          { required: true, message: "请选择源科室", trigger: "change" },
        ],
        itemCode: [
          { required: true, message: "请选择统计项目", trigger: "change" },
        ],
        piont: [
          { required: true, message: "请输入给予比例", trigger: "blur" },
        ]
      },
      showDrawer: false,
      title: "",
      tableColumns: [
        {
          title: "目标科室编码",
          dataIndex: "sdeptCode",
        },
        {
          title: "目标科室名称",
          dataIndex: "sdeptName",
        },
        {
          title: "源科室编码",
          dataIndex: "ydeptCode",
        },
        {
          title: "源科室名称",
          dataIndex: "ydeptName",
        },
        {
          title: "统计项目编码",
          dataIndex: "itemCode",
        },
        {
          title: "统计项目名称",
          dataIndex: "itemName",
        },
        {
          title: "给予比例",
          dataIndex: "piont",
        },
        {
          title: "是否计入目标科室",
          dataIndex: "isOffsetting",
          type: "otherTag",
        },
        {
          title: "操作",
          dataIndex: "caozuo",
          type: "otherTag",
          width: 160,
        },
      ],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableLoading: false,
      tableData: [],
      newCondition: {},
      elements: [
        {
          key: "period",
          label: "周期",
          type: "select",
          itemLabel: "periodPull",
          itemValue: "periodSuffix",
          hideSelectAll: true,
          options: [],
          value: "",
        },
        {
          label: "科室",
          type: "input",
          key: "dept",
          value: "",
          placeholder: "请输入目标科室编码/目标科室名称/源科室编码/源科室编码",
          width: 360,
        },
        {
          label: "统计项目",
          key: "statisticalItems",
          type: "input",
          value: '',
          placeholder: "请输入统计项目编码/统计项目名称",
          width: 240,
        },
      ],
      currentRow: {},
      selections: [],
      kzdptList: [],
      statistical: [],
      imageShow: false
    };
  },
  created() {
    this.getSelect();
  },
  methods: {
    handleSelection(row) {
      this.selections = row;
    },
    getFileInfo() {
      const id = this.elements[0].options.find(item =>item.periodSuffix===this.newCondition?.period)?.id
      getAssessmentCycleById({
        id: id,
      }).then((res) => {
        if (res.code === 200) {
          const { isFile } = res.data
          if(isFile === 1){
            this.imageShow = true;
          }else {
            this.imageShow = false;
          }
        } 
      });
    },
    getSelect() {
      // 周期
      getAssessmentCyclePull().then((res) => {
        if (res.code === 200) {
          this.elements[0].options = res.data;
          const { periodSuffix } = res.data[0];
          this.elements[0].value = periodSuffix;
          localStorage.setItem(
            "cycle",
            JSON.stringify(this.elements[0].options)
          );
          setTimeout(() => {
            this.handleSearch(this.$refs.filterForm.getParms())
          }, 1000)
        } else {
          this.$message.error(res.msg);
        }
      });
      HISDeptCode().then(res => {
        if (res.code === 200) {
          this.kzdptList = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
      listAll().then(res => {
        if (res.code === 200) {
          this.statistical = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    
    handleSubmit() {
      this.$refs["drawerForm"].validate((valid) => {
        if (/^(0(\.\d+)?|1(\.0+)?){2}$/.test(this.drawerForm.piont)) {
          this.$message.warning("给予比例只能输入0-1之间的数字,保留1位小数");
          return;
        }

        if (valid) {
          const param = {
            ...this.drawerForm
          };

          if (this.btnType === 2) {
            // 编辑
            param.id = this.currentRow?.id;
          }
          param.itemName = this.statistical.find(item => item.projectCode === this.drawerForm.itemCode)?.projectName
          param.period = this.newCondition.period
          this.qrLoading = true;
          saveOrUpdateSysItemPiont(param).then((res) => {
            this.qrLoading = false;
            if (res.code === 200) {
              this.getData();
              this.showDrawer = false;
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
          }).catch(()=>{
            this.qrLoading = false;
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 查询
    handleSearch(value) {
      this.newCondition = value;
      this.currentPage = 1;
      this.getData();
      this.getFileInfo()
    },
    // 重置
    handleReset(val) {
      // this.handleSearch(val);
    },
    handleEdit(row) {
      // 编辑
      this.currentRow = row;
      this.btnType = 2;
      this.title = "编辑";
      this.handleSetForm(row);
      this.showDrawer = true;
      this.drawerForm = row
    },
    handleSetForm(row) {
      this.$handleSetForm(this.drawerForm, 1, row);
    },
    handleDelete(row) {
      // 删除
      this.$ckConfirm({
        content: "此操作将删除该条记录，并无法恢复， 是否继续?",
        title: "提示",
        okFn: (res) => {
          deleteSysItemPiont({
            id: row.id,
          }).then((res) => {
            if (res.code === 200) {
              this.currentPage = 1;
              this.getData();
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
          });
        },
        cancelFn: (res) => {
          console.log("取消");
        },
      });
    },
    handleAdd() {
      this.btnType = 1;
      this.title = "添加";
      this.$handleSetForm(this.drawerForm, 0);
      this.drawerForm.status = "1";
      this.showDrawer = true;
    },
    getData() {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        period: this.newCondition.period,
        deptCode: this.newCondition.dept,
        keyWord: this.newCondition.statisticalItems,
      };
      this.tableLoading = true;
      listByPeriod(params)
        .then((res) => {
          this.tableLoading = false;
          if (res.code === 200) {
            this.tableData = res.data.records;
            this.total = res.data.total;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    pageChange(payload) {
      this.currentPage = payload.current;
      this.pageSize = payload.pageSize;
      this.getData();
    },
  },
};
</script>
<style lang="less" scoped>
.wraper {
  display: flex;
  height: 100%;
  overflow: hidden;
  position: relative;
  .upload-demo {
    .buttons {
      margin: 0px 5px;
      height: 27px;
      margin-top: -1px;
    }
  }
}
.image-srcc {
  width: 60px;
  height: 60px;
  // border: 1px solid red;
  position: absolute;
  top: 5px;
  left: 120px;
  z-index: 2;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
